package com.web.quartz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web.basic.service.BasicSysDictService;
import com.web.common.basic.quartz.entity.QuartzCronTask;
import com.web.common.basic.quartz.entity.QuartzIntervalTask;
import com.web.common.basic.quartz.entity.QuartzJobDetail;
import com.web.common.basic.quartz.entity.QuartzJobDetailEntity;
import com.web.common.basic.quartz.entity.QuartzJobParam;
import com.web.common.result.R;
import com.web.common.result.ResultEnum;
import com.web.common.tool.DateTimeUtil;
import com.web.quartz.mapper.QuartzJobMapper;
import com.web.service.handler.error.CustomException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Map;
import org.quartz.Trigger.TriggerState;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 定时任务名称 服务实现类
 * </p>
 *
 * @author zhouhui
 * @since 2023-08-08
 */
@Service
public class QuartzJobServiceImpl {
	
	private static final String QUARTZ_JOB_PERIOD = "quartz_job_period";
	
	@Autowired
	private QuartzJobMapper quartzJobMapper;
	
	@Autowired
	private QuartzOperateServiceImpl quartzOperateServiceImpl;
	
	@Autowired
	private BasicSysDictService basicSysDictService;
	
	/**
	 * 查询定时任务数据列表
	 * 
	 * @param condition 查询条件
	 * @return R<IPage<QuartzJobExecEntity>> 数据列表
	 *
	 * @author zhouhui
	 * @since 2023.08.09
	 */
	public R<IPage<QuartzJobDetail>> getJobList(QuartzJobDetailEntity condition) {
		R<IPage<QuartzJobDetail>> json = new R<>();
		setSearchCondition(condition);
		Page<QuartzJobDetail> page = new Page<>(condition.getPage(), condition.getSize());
		IPage<QuartzJobDetail> result = quartzJobMapper.getQuartzJobList(page, condition);
		if (result == null) {
			throw new CustomException(ResultEnum.DATA_QUERY_ERROR.getMessage());
		}
		ArrayList<String> typeList = new ArrayList<>();
		typeList.add(QUARTZ_JOB_PERIOD);
		Map<String, String> typeMap = basicSysDictService.getDictMap(typeList);
		for(QuartzJobDetail item: result.getRecords()) {
			item.setStartTime(longToLocalDateTime(item.getStartTimeNum()));
			item.setEndTime(longToLocalDateTime(item.getEndTimeNum()));
			item.setNextFireTime(longToLocalDateTime(item.getNextFireTimeNum()));
			item.setTriggerTypeName(typeMap.get(item.getTriggerType()));
			if(TriggerState.PAUSED.name().equals(item.getTriggerState())) {
				item.setJobStatus(1);
			}else {
				item.setJobStatus(0);
			}
		}
		json.setResultEnum(ResultEnum.SUCCESS);
		json.setData(result);
		return json;
	}
	
	/**
	 * 获取定时任务的详细信息
	 * @param job 查询条件
	 * @return 定时任务详细信息
	 *
	 * @author zhouhui
	 * @since 2023.11.19
	 */
	public R<QuartzJobParam> getJobDetail(QuartzJobParam job) {
		QuartzJobDetail jobDetail = quartzJobMapper.getJobDetail(job);
		if(jobDetail == null) {
			throw new CustomException("没有查询到定时任务信息");
		}
		job.setJobGroup(jobDetail.getJobGroup());
		job.setJobClassName(jobDetail.getJobClassName());
		job.setDescription(jobDetail.getDescription());
		if(jobDetail.getStartTimeNum() != null && jobDetail.getStartTimeNum() > 0) {
			job.setStartAt(DateTimeUtil.localDateTimeToDate(longToLocalDateTime(jobDetail.getStartTimeNum())));
		}
		if(jobDetail.getEndTimeNum() != null && jobDetail.getEndTimeNum() > 0) {
			job.setEndAt(DateTimeUtil.localDateTimeToDate(longToLocalDateTime(jobDetail.getEndTimeNum())));
		}
		if("CRON".equals(jobDetail.getTriggerType())) {
			job.setQuartzType(1);
			QuartzJobParam result = quartzJobMapper.getCronTrigger(job);
			if(result == null) {
				throw new CustomException("获取cron表达式信息失败");
			}
			job.setCron(result.getCron());
		}else if("DAILY_I".equals(jobDetail.getTriggerType())) {
			job.setQuartzType(0);
			QuartzJobParam result = quartzJobMapper.getSimpropTrigger(job);
			if(result == null) {
				throw new CustomException("获取固定频率信息失败");
			}
			job.setInterval(result.getInterval());
			job.setRepeatCount(result.getRepeatCount() + 1);
		}
		return R.ok(job);
	}
	
	/**
	 * 将时间戳转成LocalDateTime
	 * @param unixTime 时间戳
	 * @return
	 *
	 * @author zhouhui
	 * @since 2023.11.10 
	 */
	private LocalDateTime longToLocalDateTime(Long unixTime) {
		if(unixTime > 0) {
			return DateTimeUtil.longToLocalDateTime(unixTime);
		}else {
			return null;
		}
	}

	/**
	 * 新增定时任务信息。 注：针对HTTP请求地址是否正确，Bean是否存在，在实际执行时再进行校验。
	 * 
	 * @param job 任务信息
	 * @return R<Object> 处理结果
	 *
	 * @author zhouhui
	 * @since 2023.08.11
	 */
	public R<Object> saveQuartzJob(QuartzJobParam job) {
		R<Object> json = new R<>();
		boolean isSuccess = false;
		if (job.getQuartzType() == 1) {
			//cron
			QuartzCronTask task = new QuartzCronTask();
			BeanUtils.copyProperties(job, task);
			isSuccess = quartzOperateServiceImpl.cronSimpleQuartz(task);
		} else if (job.getQuartzType() == 0) {
			//固定频率
			QuartzIntervalTask task = new QuartzIntervalTask();
			BeanUtils.copyProperties(job, task);
			isSuccess = quartzOperateServiceImpl.intervalSimpleQuartz(task);
		}else {
			throw new CustomException("选择的任务类型错误");
		}
		if(isSuccess) {
			json.setResultEnum(ResultEnum.SUCCESS);
			return json;
		}else {
			json.setResultEnum(ResultEnum.ERROR);
			json.setMessage("定时任务创建失败");
			return json;
		}
	}

	/**
	 * 删除定时任务信息
	 * 
	 * @param job 任务信息
	 * @return R<Object> 处理结果
	 *
	 * @author zhouhui
	 * @since 2023.08.14
	 */
	public R<Object> deleteQuartzJob(QuartzJobParam job) {
		R<Object> json = new R<>();
		boolean isSuccess = quartzOperateServiceImpl.deleteQuartzJob(job.getJobName(), job.getJobGroup());
		if(!isSuccess) {
			json.setResultEnum(ResultEnum.ERROR);
			json.setMessage("删除定时任务失败！");
			return json;
		}
		json.setResultEnum(ResultEnum.SUCCESS);
		return json;
	}

	/**
	 * 启用或者停用定时任务
	 * 
	 * @param job 任务信息
	 * @return R<Object> 处理结果
	 *
	 * @author zhouhui
	 * @since 2023.08.14
	 */
	public R<Object> runOrStopQuartzJob(QuartzJobParam job) {
		R<Object> json = new R<>();

		quartzOperateServiceImpl.quartzPauseResume(job.getJobName(), job.getJobGroup());
		
		json.setResultEnum(ResultEnum.SUCCESS);
		return json;
	}
	
	/**
	 * 手动触发执行一次定时任务。
	 * @param job 任务信息
	 * @return R<Object> 处理结果
	 *
	 * @author zhouhui
	 * @since 2023.08.15 
	 */
	public R<Object> executeOnceQuartzJob(QuartzJobParam job) {
		R<Object> json = new R<>();
		quartzOperateServiceImpl.execJobOneTimes(job.getJobName(), job.getJobGroup());
		json.setResultEnum(ResultEnum.SUCCESS);
		return json;
	}
	

	/**
	 * 设置查询条件
	 * 
	 * @param condition 查询条件
	 *
	 * @author zhouhui
	 * @since 2023.08.09
	 */
	private void setSearchCondition(QuartzJobDetailEntity condition) {
		if (StringUtils.hasText(condition.getJobName())) {
			condition.setJobName("%" + condition.getJobName() + "%");
		}
	}
}
